class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (!root) return {};
        queue<pair<TreeNode *, int>> q;
        q.push({root,0});
        vector<vector<int>> v;
    
        while (!q.empty()) {
            auto front = q.front();
            auto node = front.first;
            auto level = front.second;
            q.pop();
            if (!node) continue;
            q.push({node->left, level + 1});
            q.push({node->right, level + 1});
            if (v.size() < level + 1) v.push_back({});
            v[level].emplace_back(node->val);
        }
        return v;
    }
};